package com.ns.scs.user.controller;

import com.ns.basic.server.entry.ServerEntry;
import com.ns.basic.server.service.IServerService;
import com.ns.core.annotations.ReqLog;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.current.config.SysConst;
import com.ns.core.sentinel.LimitType;
import com.ns.core.sentinel.RateLimiter;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.cache.RedisUtil;
import com.ns.core.utils.jwt.SystemUtil;
import com.ns.core.utils.sg.NbUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.utils.sg.ResultOk;
import com.ns.core.vo.au.SsoUserVO;
import com.ns.scs.msg.service.IMsgService;
import com.ns.scs.user.bo.ScsUserBO;
import com.ns.scs.user.entry.ScsUser;
import com.ns.scs.user.entry.UserServer;
import com.ns.scs.user.service.IScsUserService;
import com.ns.scs.user.service.IUserServerService;
import com.ns.scs.user.vo.ScsUserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 业务用户登录注册接口
 *
 * @author lw
 */
@RestController
@RequestMapping
@RequiredArgsConstructor
@CrossOrigin
public class LoginController {

    private final IScsUserService service;

    private final IUserServerService ursService;

    private final IServerService serverService;

    private final IMsgService msgService;

    /**
     * 业务用户登录：账户、密码登录
     *
     * @param user 用户名
     * @param pwd  参数
     */
    @GetMapping("user/login")
    @ReqLog(module = "用户模块", name = "登录", authFlag = false)
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk doLogin(String user, String pwd) {
        // 1、验证参数
        if (NbUtil.hasNull(user, pwd)) {
            return ResultOk.getError("请输入用户名/密码");
        }
        return ResultOk.getSuccessData(service.doLogin(user, pwd));
    }

    /**
     * 注册
     */
    @PostMapping("user/register")
    @ReqLog(module = "用户模块", name = "注册", authFlag = false)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public ResultOk register(@RequestBody ScsUserBO userBO) {
        // 获取服务
        Long sid = StpUtil.getSid();
        ServerEntry serverEntry = serverService.getById(sid);
        if (ObjectUtils.isEmpty(serverEntry)) {
            throw new ResultError("服务不存在");
        }

        ScsUser user = new ScsUser();
        BeanUtils.copyProperties(userBO, user);
        long sort = service.getMaxSort();
        user.setSort(sort + 1);
        boolean flag = service.save(user);
        if (flag) {
            // 密码加密
            String passwordMd5;
            if (Objects.nonNull(user.getPwd())) {
                passwordMd5 = SystemUtil.getPasswordMd5(user.getId(), user.getPwd());
            } else {
                passwordMd5 = SystemUtil.getPasswordMd5(user.getId(), user.getPhone());
            }
            user.setPwd(passwordMd5);
            flag = service.updateById(user);
        } else {
            throw new ResultError("用户保存失败！");
        }
        if (flag && Objects.nonNull(StpUtil.getSid())) {
            UserServer bu = new UserServer();
            bu.setUid(user.getId());
            bu.setSid(StpUtil.getSid());
            flag = ursService.saveOrUpdate(bu);
        }
        if (flag) {
            // 模板
            String msgTemplate = "欢迎您,【%s】 第 %s 位成员！👏";
            // 获取用户数
            String count = RedisUtil.get(SysConst.PROJECT_TAG + SymbolsMark.COLON + SysConst.SBS_USER_COUNT);
            // 注册成功，发送站内消息
            List<String> params = new ArrayList<>();
            params.add(serverEntry.getName());
            Long num = (StringUtils.hasText(count) ? Long.parseLong(count) : 0L) + 1;
            params.add(String.valueOf(num));
            String msg = msgService.sendInnerMsg(user.getId(), sid, msgTemplate, params);
            return ResultOk.getSuccess(msg);
        } else {
            throw new ResultError("用户关联信息保存失败！");
        }
    }


    /**
     * 获取当前用户
     */
    @GetMapping("/cur/getUserById")
    @ReqLog(module = "用户模块", name = "获取当前用户")
    ResultOk getUserById() {
        SsoUserVO ssoUserVO = StpUtil.getCurUser();
        if (ObjectUtils.isEmpty(ssoUserVO)) {
            return ResultOk.getError("用户未登录");
        }
        ScsUser data = service.getById(ssoUserVO.getId());
        ScsUserVO vo = new ScsUserVO();
        BeanUtils.copyProperties(data, vo);
        return ResultOk.getSuccessData(vo);
    }
}
